﻿using System;
using System.Diagnostics;
using System.Linq;
using EPiServer.Community.Blog;
using EPiServer.Find;
using StructureMap;

namespace JoelAbrahamsson.Web.Jobs
{
    [EPiServer.PlugIn.ScheduledPlugIn(DisplayName = "Reindex")]
    public class SearchIndexingJob
    {
        public static string Execute()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var blog = BlogHandler.GetBlog(2);
            int entryCount;
            var allEntries = blog.GetEntries(DateTime.MinValue, DateTime.Now, EntryPublishState.Published, 1, int.MaxValue - 1, out entryCount);
            var client = ObjectFactory.GetInstance<IClient>();
            Stopwatch indexingStopwatch = new Stopwatch();
            indexingStopwatch.Start();
            //foreach (var entry in allEntries)
            //{
            //    client.Index(entry);
            //}
            var indexingCount = 0;
            for (int i = 0; i * 20 < entryCount; i++)
            {
                var batch = allEntries.Skip(i*20).Take(20).ToList();
                indexingCount = indexingCount + batch.Count;
                var indexingResult = client.Index(batch);
                foreach (var bulkResultItem in indexingResult.Items)
                {
                    if (!bulkResultItem.Ok)
                    {
                        throw new Exception("Failed to index " + bulkResultItem.Id + ". Error: " + bulkResultItem.Error);
                    }
                }
            }
            indexingStopwatch.Stop();
            stopwatch.Stop();

            return "Indexed " + indexingCount + " blog posts. Indexing complete. Took: " + stopwatch.ElapsedMilliseconds + "ms. Indexing took: " + indexingStopwatch.ElapsedMilliseconds + "ms.";
        }
    }
}